<?php

require_once('Zend/Controller/Plugin/Abstract.php');

/**
 * Plugin d'initialisation
 * 
 * @uses Zend_Controller_Plugin_Abstract
 */
class Myzen_Controller_Plugin_ModuleRoute extends Zend_Controller_Plugin_Abstract
{
	
	
	public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $paramsList = preg_split  ( '/\//' ,  $request->getPathInfo());
		$moduleName = $paramsList[1];
		if(empty($moduleName)) return;
		if(preg_match('/[^a-z]/',$moduleName)) return;
  		if(32 < strlen($moduleName)) return;
		//now we should be safe to look for motential routing
		$potentialConf = ROOT_PATH.'/app/src/modules/'.$moduleName.'/route.ini';
		if(is_file($potentialConf)) {
			//User defined some special routes for the module, we try loading them	
			Zend_Registry::get('app_log')->log('loading custom route for module '.$moduleName,Zend_Log::DEBUG);
			
			//environment variable to check what needs to be loaded
			$env = getenv("ZF_ENV");
			if(empty($env)) $env = 'production';
			
			$front = Zend_Controller_Front::getInstance(); 
			$router = $front->getRouter();
			
			//We may have an issue on a route if the environment is not production in this case, we fallback on production one
			try{
				$config = new Zend_Config_Ini($potentialConf, $env);
			} catch(Zend_Config_Exception $e) {
				if('production' != $env) {
					Zend_Registry::get('app_log')->log('environment  '.$env.' not defined on route file, fallbacking to production one',Zend_Log::DEBUG);
					$config = new Zend_Config_Ini($potentialConf, 'production');
				} else {
					Zend_Registry::get('app_log')->log('Route ini file badly formatted for '.$potentialConf,Zend_Log::CRIT);
					require_once(Zend/Config/Exception.php);
					throw new Zend_Config_Exception($e->getMessage());	
				}
			}
			
			$router->addConfig($config, 'routes');
			
				
		}
		
    }//end routestartup
    
} //end plugin